<!DOCTYPE html>
<html>
  <head>
    <title>贪吃蛇小游戏</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="300" height="300"></canvas>
     <script>
		 // 定义游戏画布和上下文
		 const canvas = document.getElementById('canvas');
		 const ctx = canvas.getContext('2d');
		 
		 // 定义方格大小和数量
		 const grid = 10;
		 const width = canvas.width / grid;
		 const height = canvas.height / grid;
		 
		 // 初始化贪吃蛇
		 let snake = [
		   { x: 5, y: 5 },
		   { x: 4, y: 5 },
		   { x: 3, y: 5 }
		 ];
		 
		 // 初始化食物位置
		 let food = {
		   x: Math.floor(Math.random() * width),
		   y: Math.floor(Math.random() * height)
		 };
		 
		 // 初始化贪吃蛇方向
		 let direction = 'right';
		 
		 // 游戏循环
		 function gameLoop() {
		   // 移动贪吃蛇
		   let head = { x: snake[0].x, y: snake[0].y };
		   switch (direction) {
		     case 'up':
		       head.y--;
		       break;
		     case 'down':
		       head.y++;
		       break;
		     case 'left':
		       head.x--;
		       break;
		     case 'right':
		       head.x++;
		       break;
		   }
		   snake.unshift(head);
		 
		   // 判断贪吃蛇是否吃到食物
		   if (head.x === food.x && head.y === food.y) {
		     food = {
		       x: Math.floor(Math.random() * width),
		       y: Math.floor(Math.random() * height)
		     };
		   } else {
		     snake.pop();
		   }
		 
		   // 清空画布
		   ctx.clearRect(0, 0, canvas.width, canvas.height);
		 
		   // 绘制食物
		   ctx.fillStyle = 'red';
		   ctx.fillRect(food.x * grid, food.y * grid, grid, grid);
		 
		   // 绘制贪吃蛇
		   ctx.fillStyle = 'green';
		   snake.forEach((segment) => {
		     ctx.fillRect(segment.x * grid, segment.y * grid, grid, grid);
		   });
		 
		   // 检查游戏是否结束
		   if (
		     head.x < 0 || head.x >= width ||
		     head.y < 0 || head.y >= height ||
		     snake.slice(1).some((segment) => segment.x === head.x && segment.y === head.y)
		   ) {
		     alert('游戏结束！');
		     clearInterval(intervalId);
		   }
		 }
		 
		 // 监听键盘事件
		 document.addEventListener('keydown', (event) => {
		   switch (event.key) {
		     case 'ArrowUp':
		       direction = 'up';
		       break;
		     case 'ArrowDown':
		       direction = 'down';
		       break;
		     case 'ArrowLeft':
		       direction = 'left';
		       break;
		     case 'ArrowRight':
		       direction = 'right';
		       break;
		   }
		 });
		 
		 // 开始游戏
		const intervalId = setInterval(gameLoop, 100);

		 
		 
		 
	 </script> 
	 
	 </body>
</html>